package com.hais1992.oneday.activity;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.Toast;

import com.hais1992.oneday.R;
import com.hais1992.oneday.common.Config;
import com.hais1992.oneday.common.JsonToObjectList;
import com.hais1992.oneday.dao.ArticleAdapter;
import com.hais1992.oneday.entity.Article;
import com.hais1992.oneday.entity.Type;
import com.hais1992.oneday.entity.User;
import com.hais1992.oneday.listener.MenuListener;
import com.hais1992.oneday.listener.UserListener;
import com.hais1992.oneday.tools.GetHttpData;
import com.hais1992.oneday.tools.GetHttpData.GetCallback;
import com.hais1992.oneday.tools.iscroll.XListView;
import com.hais1992.oneday.tools.iscroll.XListView.IXListViewListener;

/**
 * 軟件主界面
 * 
 * @author Hello_海生
 * @date 2014年5月26日
 */
public class MainActivity extends Activity implements IXListViewListener {
	private XListView listView; // 上啦刷機 List
	private Handler iscrollhandler; // 設置 iscroll 的傳輸

	private ImageView userImg; // 右邊的 個人中心
	private ImageView menuImg; // 左邊的 菜單按鈕

	private List<Map<String, Object>> articleList = null; // 文章List
	private ArticleAdapter adapter = null; // 文章適配器

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		listView = (XListView) findViewById(R.id.articleList);
		menuImg = (ImageView) findViewById(R.id.leftImg);
		userImg = (ImageView) findViewById(R.id.rightImg);

		// 設置 菜單 按鈕事件
		MenuListener menuListener = new MenuListener();
		menuImg.setOnClickListener(menuListener);

		// 設置個人中心 菜單按鈕點擊事件
		UserListener userListener = new UserListener();
		userImg.setOnClickListener(userListener);

		// 獲取 json 數據，開始加載界面
		Intent i = getIntent();
		String json = i.getStringExtra("json");
		articleList = JsonToObjectList.articleList(json);

		// 設置上啦刷新
		listView.setPullLoadEnable(true);
		listView.setPullRefreshEnable(false); // 禁用上啦加載

		adapter = new ArticleAdapter(this, articleList);
		listView.setAdapter(adapter);
		listView.setXListViewListener(this);
		iscrollhandler = new Handler(); // 開始艦艇

		
		
		//监听ListView点击事件
	    listView.setOnItemClickListener(new OnItemClickListener() {
			@SuppressLint("SimpleDateFormat") @Override
			public void onItemClick(AdapterView<?> arg0, View position, int id,long arg3) {
				id=(int) adapter.getItemId(id-1);
				System.out.println("用户点击:"+articleList.get(id).get("title"));
				Intent i = new Intent(MainActivity.this, ShowArticleActivity.class);

				//处理分类信息
				Type type = com.alibaba.fastjson.JSONObject.parseObject(articleList.get(id).get("typeId")+"", Type.class);
				User user = com.alibaba.fastjson.JSONObject.parseObject(articleList.get(id).get("userId")+"", User.class);
				//转换日期
				SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String insertTime = formatter.format(articleList.get(id).get("insertTime"));
				//存储内容到 实体类
				Article article = new Article();
				article.setId(Long.parseLong(articleList.get(id).get("id").toString()));
				article.setTitle(articleList.get(id).get("title").toString());
				article.setInsertTime(insertTime);
				article.setSource(articleList.get(id).get("source").toString());
				article.setContent(articleList.get(id).get("content").toString());
				article.setTypeId(type);
				article.setUserId(user);
				
				Bundle bundle = new Bundle();
				bundle.putSerializable("article", article);
				i.putExtra("bundle", bundle);
				MainActivity.this.startActivity(i);
			}
		});
		
		
		
		
		
	}

	
	
	
	
	
	
	
	
	
	
	@Override
	public void onRefresh() {
	}

	@Override
	// 上啦加載更多
	public void onLoadMore() {
		iscrollhandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				System.out.println("-------上拉加載 更多---------");
				adapter.notifyDataSetChanged();

				Map<String, String> map = new HashMap<String, String>();
				map.put("start", articleList.size() + "");
				map.put("count", Config.PAGE_NUNBER);
				map.put("key", Config.SERVER_KEY);

				new GetHttpData(Config.SERVER_URL + Config.GET_LIST_URL, "POST",
						map, new GetCallback() {
							@Override
							public void onSuccess(String result) {
								List<Map<String, Object>> loadList = JsonToObjectList.articleList(result);
								if (loadList.size() == 0) {
									Toast.makeText(getApplicationContext(),"沒有更老的文章了。。", Toast.LENGTH_SHORT).show();
								} else {
									articleList.addAll(loadList);
									adapter = new ArticleAdapter(MainActivity.this, articleList);
								}
								listView.stopLoadMore(); // 更新完后 恢復狀態
							}
						});

			}
		}, 2000);
	}

	// 返回键
	boolean isExit = false;
	@SuppressLint("HandlerLeak") Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			isExit = false;
		}

	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (!isExit) {
				isExit = true;
				Toast.makeText(getApplicationContext(), "再按一次退出程序",
						Toast.LENGTH_SHORT).show();
				// 利用handler延迟发送更改状态信息
				mHandler.sendEmptyMessageDelayed(0, 2000);
			} else {
				finish();
				System.exit(0);
			}
		}
		return false;
	}
}
